import { getTabbarPages } from './pages'
import useSystemStore from '@/stores/system'
import useMemberStore from '@/stores/user'
/**
 * 跳转页面
 */
export const goTo = (redirect : any) => {
	// console.log(redirect)
	let { url, mode, param, success, fail, complete } = redirect



	//不需要登录操作的页面
	const unloginList = [
		'/pages/auth/register',
		'/pages/auth/phone_login',
		'/pages/auth/password_login',
		'/pages/index/index',
		'/pages/help/list',
		'/pages/help/safe',
		'/pages/help/detail',
		'/pages/user/help',
	];

	if (!getToken() && !unloginList.includes(url)) {
		url = '/pages/auth/login'
		mode = 'navigateTo'
	}

	mode = mode || 'navigateTo'
	const tabBar = getTabbarPages()
	tabBar.includes(url) && (mode = 'switchTab')
	mode != 'switchTab' && param && Object.keys(param).length && (url += queryParams(param))
	switch (mode) {
		case 'switchTab':
			uni.switchTab({
				url,
				success: () => {
					success && success()
				},
				fail: () => {
					fail && fail()
				},
				complete: () => {
					complete && complete()
				}
			})
			break;
		case 'navigateTo':
			uni.navigateTo({
				url,
				success: () => {
					success && success()
				},
				fail: () => {
					fail && fail()
				},
				complete: () => {
					complete && complete()
				}
			})
			break;
		case 'reLaunch':
			uni.reLaunch({
				url,
				success: () => {
					success && success()
				},
				fail: () => {
					fail && fail()
				},
				complete: () => {
					complete && complete()
				}
			})
			break;
		case 'redirectTo':
			uni.redirectTo({
				url,
				success: () => {
					success && success()
				},
				fail: (err) => {
					fail && fail()
				},
				complete: () => {
					complete && complete()
				}
			})
			break;
	}
}
export function makephone(phone:any){
	uni.makePhoneCall({
		phoneNumber:phone
	})
}
/**
 * @description 对象转url参数
 * @param {object} data,对象
 * @param {Boolean} isPrefix,是否自动加上"?"
 * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
 */
export function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
	const prefix = isPrefix ? '?' : ''
	const _result = []
	if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets'
	for (const key in data) {
		const value = data[key]
		// 去掉为空的参数
		if (['', undefined, null].indexOf(value) >= 0) {
			continue
		}
		// 如果值为数组，另行处理
		if (value.constructor === Array) {
			// e.g. {ids: [1, 2, 3]}
			switch (arrayFormat) {
				case 'indices':
					// 结果: ids[0]=1&ids[1]=2&ids[2]=3
					for (let i = 0; i < value.length; i++) {
						_result.push(`${key}[${i}]=${value[i]}`)
					}
					break
				case 'brackets':
					// 结果: ids[]=1&ids[]=2&ids[]=3
					value.forEach((_value) => {
						_result.push(`${key}[]=${_value}`)
					})
					break
				case 'repeat':
					// 结果: ids=1&ids=2&ids=3
					value.forEach((_value) => {
						_result.push(`${key}=${_value}`)
					})
					break
				case 'comma':
					// 结果: ids=1,2,3
					let commaStr = ''
					value.forEach((_value) => {
						commaStr += (commaStr ? ',' : '') + _value
					})
					_result.push(`${key}=${commaStr}`)
					break
				default:
					value.forEach((_value) => {
						_result.push(`${key}[]=${_value}`)
					})
			}
		} else {
			_result.push(`${key}=${value}`)
		}
	}
	return _result.length ? prefix + _result.join('&') : ''
}
/**
 * 获取token
 * @returns
 */
export function getToken() : null | string {

	return useMemberStore().token
	//return uni.getStorageSync(import.meta.env.VITE_REQUEST_STORAGE_TOKEN_KEY);
	// return null;
}

/**
 * 设置token
 * @param token
 * @returns
 */
export function setToken(token : string) : void {
	//uni.setStorageSync(import.meta.env.VITE_REQUEST_STORAGE_TOKEN_KEY, token)
	uni.setStorageSync('token', token)
}

/**
 * 移除token
 * @returns
 */
export function removeToken() : void {
	uni.removeStorageSync("token")
	//uni.removeStorageSync(import.meta.env.VITE_REQUEST_STORAGE_TOKEN_KEY)
}

/**
 * 将url 解构为 { path: ***, query: {} }
 */
export function urlDeconstruction(url : string) {
	const query : any = {}
	const [path, param] = url.split('?')

	param && param.split('&').forEach((str : string) => {
		let [name, value] = str.split('=')
		query[name] = value
	})

	return { path, query }
}

/**
 * 判断是否是url
 * @param str
 * @returns
 */
export function isUrl(str : string) : boolean {
	return str && (str.indexOf('http://') != -1 || str.indexOf('https://') != -1) || false
}

/**
 * 图片输出
 * @param path
 * @returns
 */
export function imgUrl(path : string) : string {
	return isUrl(path) ? path : `${import.meta.env.VITE_IMG_DOMAIN}/${path}`
}

/**
 * 手机号隐藏
 */
export function mobileHide(mobile : string) {
	return mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

/**
 * 判断是否是微信浏览器
 */
export function isWeixinBrowser() : boolean {
	// #ifndef H5
	return false
	// #endif
	let ua = navigator.userAgent.toLowerCase()
	return /micromessenger/.test(ua) ? true : false
}

/**
 * 获取应用场景值
 */
export function getAppChannel() : string {
	// #ifdef APP-PLUS
	return 'app'
	// #endif
	// #ifdef MP-WEIXIN
	return 'weapp'
	// #endif
	// #ifdef H5
	return isWeixinBrowser() ? 'wechat' : 'h5'
	// #endif
}

/**
 * 金额格式化
 */
export function moneyFormat(money : string) : string {
	return isNaN(parseFloat(money)) ? money : parseFloat(money).toFixed(2)
}

/**
 * 手机号隐藏
 */
export function mobileConceal(mobile : string) : string {
	return mobile.substring(0, 3) + "****" + mobile.substr(mobile.length - 4);
}

/**
 * 时间戳转日期格式
 * @param timeStamp
 * @param type
 */
export function timeStampTurnTime(timeStamp : any, type = "") {
	if (timeStamp != undefined && timeStamp != "" && timeStamp > 0) {
		var date = new Date();
		date.setTime(timeStamp * 1000);
		var y = date.getFullYear();
		var m : any = date.getMonth() + 1;
		m = m < 10 ? ('0' + m) : m;
		var d : any = date.getDate();
		d = d < 10 ? ('0' + d) : d;
		var h : any = date.getHours();
		h = h < 10 ? ('0' + h) : h;
		var minute : any = date.getMinutes();
		var second : any = date.getSeconds();
		minute = minute < 10 ? ('0' + minute) : minute;
		second = second < 10 ? ('0' + second) : second;
		if (type) {
			if (type == 'yearMonthDay') {
				return y + '年' + m + '月' + d + '日';
			}
			return y + '-' + m + '-' + d;
		} else {
			return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
		}

	} else {
		return "";
	}
}

/**
 * 日期格式转时间戳
 * @param {Object} date
 */
export function timeTurnTimeStamp(date : string) {
	var f = date.split(' ', 2);
	var d = (f[0] ? f[0] : '').split('-', 3);
	var t = (f[1] ? f[1] : '').split(':', 3);
	return (new Date(
		parseInt(d[0], 10) || null,
		(parseInt(d[1], 10) || 1) - 1,
		parseInt(d[2], 10) || null,
		parseInt(t[0], 10) || null,
		parseInt(t[1], 10) || null,
		parseInt(t[2], 10) || null
	)).getTime() / 1000;
}

/**
 * 复制
 * @param {Object} value
 * @param {Object} callback
 */
export function copy(value : any, callback : any) {
	// #ifdef H5
	var oInput = document.createElement('input'); //创建一个隐藏input（重要！）
	oInput.value = value; //赋值
	oInput.setAttribute("readonly", "readonly");
	document.body.appendChild(oInput);
	oInput.select(); // 选择对象
	document.execCommand("Copy"); // 执行浏览器复制命令
	oInput.className = 'oInput';
	oInput.style.display = 'none';
	uni.hideKeyboard();
	uni.showToast({
		title: '复制成功',
		icon: 'none'
	});

	typeof callback == 'function' && callback();
	// #endif

	// #ifdef MP || APP-PLUS
	uni.setClipboardData({
		data: value,
		success: () => {
			typeof callback == 'function' && callback();
		},
		fail: (res) => {
			// 在隐私协议中没有声明chooseLocation:fail api作用域
			if (res.errMsg && res.errno) {
				if (res.errno == 104) {
					let msg = '用户未授权隐私权限，设置剪贴板数据失败';
					uni.showToast({ title: msg, icon: 'none' })
				} else if (res.errno == 112) {
					let msg = '隐私协议中未声明，设置剪贴板数据失败';
					uni.showToast({ title: msg, icon: 'none' })
				} else {
					uni.showToast({ title: res.errMsg, icon: 'none' })
				}
			}
		}
	});
	// #endif
}

/**
 * 处理onLoad传递的参数
 * @param option
 */
export function handleOnloadParams(option : any) {
	let params : any = {};

	// 处理小程序扫码进入的场景值参数
	if (option.scene) {
		var sceneParams = decodeURIComponent(option.scene).split('&');
		if (sceneParams.length) {
			sceneParams.forEach(item => {
				let arr = item.split('-');
				params[arr[0]] = arr[1];
				if (arr[0] == 'mid') {
					uni.setStorageSync('pid', arr[1])
				}
			});
		}
	} else {
		params = option;
	}
	return params;
}

/**
 * 获取定位信息
 */
export function getLocation(param : any = {}) {
	uni.getLocation({
		type: param.type || 'gcj02',
		success: res => {
			const systemStore = useSystemStore()
			systemStore.setLocation(res);
			typeof param.success == 'function' && param.success(res);
		},
		fail: res => {
			typeof param.fail == 'function' && param.fail(res);
		},
		complete: res => {
			typeof param.complete == 'function' && param.complete(res);
		}
	});
}

/**
 * 定位信息（缓存）
 */
export function locationStorage() {
	let data = uni.getStorageSync('location');
	let mapConfig = uni.getStorageSync('mapConfig');
	if (data) {
		var date = new Date();
		if (mapConfig.valid_time > 0) {
			data.is_expired = (date.getTime() / 1000) > data.valid_time; // 是否过期
		} else {
			data.is_expired = false;
		}
	}
	return data;
}

/**
 * @description 深度克隆
 * @param {object} obj 需要深度克隆的对象
 * @returns {*} 克隆后的对象或者原值（不是对象）
 */
export function deepClone(obj : any) {
	// 对常见的“非”值，直接返回原来值
	if ([null, undefined, NaN, false].includes(obj)) return obj
	if (typeof obj !== 'object' && typeof obj !== 'function') {
		// 原始类型直接返回
		return obj
	}
	const o = isArray(obj) ? [] : {}
	for (const i in obj) {
		if (obj.hasOwnProperty(i)) {
			o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
		}
	}
	return o
}

/**
 * 防抖函数
 * @param fn
 * @param delay
 * @returns
 */
export function debounce(fn : (args ?: any) => any, delay : number = 300) {
	let timer : null | number = null
	return function (...args) {
		if (timer != null) {
			clearTimeout(timer)
			timer = null
		}
		timer = setTimeout(() => {
			fn.call(this, ...args)
		}, delay);
	}
}

const isArray = (value : any) => {
	if (typeof Array.isArray === 'function') {
		return Array.isArray(value)
	}
	return Object.prototype.toString.call(value) === '[object Array]'
}

// px转rpx
export function pxToRpx(px : any) {
	const screenWidth = uni.getSystemInfoSync().screenWidth;
	return (750 * Number.parseInt(px)) / screenWidth;
}

// 返回上一页
export function goback(data : any) {
	let { url, mode, param, title } = data
	uni.showToast({
		title: title,
		icon: 'none'
	});
	setTimeout(() => {
		if (getCurrentPages().length > 1) {
			uni.navigateBack({
				delta: 1
			});
		} else {
			redirect({
				url: url,
				param: param || {},
				mode: mode || 'redirectTo'
			});
		}
	}, 600);
}

// px转rpx
export function numberToDiscount(num : number) {
	if (!isNaN(num)) {
		if (num % 10 === 0) {
			return `${num / 10}`;
		} else {
			return num;
		}
	}
	return '';
}

export function isTimeWithinRange(time : Date, start : string, end : string) : boolean {
	// 将时间段字符串解析为小时和分钟
	const [startHour, startMinute] = start.split(':').map(Number);
	const [endHour, endMinute] = end.split(':').map(Number);

	// 获取给定时间的小时和分钟
	const hour = time.getHours();
	const minute = time.getMinutes();

	// 比较时间
	if (hour < startHour || hour > endHour) {
		return false;
	}

	if (hour === startHour && minute < startMinute) {
		return false;
	}

	if (hour === endHour && minute > endMinute) {
		return false;
	}

	return true;
}

export function getFutureTimeRanges(timeRanges: string[][]): string[][] {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();

  const futureTimeRanges: string[][] = [];

  for (const range of timeRanges) {
    const [start, end] = range.map(time => {
      const [hour, minute] = time.split(':').map(Number);
      return { hour, minute };
    });

    // 检查当前时间是否在当前时间段之前
    if (
      (currentHour < start.hour || (currentHour === start.hour && currentMinute < start.minute)) ||
      (currentHour < end.hour || (currentHour === end.hour && currentMinute < end.minute))
    ) {
      futureTimeRanges.push(range);
    }
  }

  return futureTimeRanges;
}

//获取当前几天后的日期
export function getFutureDays(dayNum:number,laterNum:number){
	
	const dayOptions = [];	
	for (let i = laterNum; i < dayNum + laterNum; i++) {
		const date = new Date();
		date.setDate(date.getDate() + i);
		
		let v = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
		let label = `${date.getMonth()}月${date.getDate()}日`;
		switch (i) {
			case 0:
				label = '今天';
				break;
			case 1:
				label = '明天';
				break;
			case 2:
				label = '后天';
				break;
			default:
				break;
		}
		dayOptions.push({
			label:label,
			value:v
		});
	}
	return dayOptions;
}